package what.the.fun.dao;

import java.util.List;

import what.the.fun.domain.User;
import what.the.fun.jdbc.UserRowMapper;

import java.util.ArrayList;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDAOImpl implements UserDAO{

	@Autowired
	DataSource dataSource;
	
	@Override
	public void insertData(User user) {
		/*String sql = "INSERT INTO user "
			    + "(user_id,first_name,last_name, gender, city) VALUES (?, ?, ?, ?,?)";
		
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

		jdbcTemplate.update(sql,
					  		new Object[] {1, user.getFirstName(), user.getLastName(),
					  		user.getGender(), user.getCity() });*/
		
		// USER STORE PROCEDURE
		String sql = "call sp_user_Insert (?, ?)";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.update(sql,
							user.getName(),
							user.getPassword());
	}

	@Override
	public List<User> getUserList() {
		List<User> userList = new ArrayList<User>();
		String sql = "call sp_user_GetAll()";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		userList = jdbcTemplate.query(sql, new UserRowMapper());
		
		return userList;
	}

	@Override
	public void updateData(User user) {
		/*String sql = "UPDATE user set first_name = ?,last_name = ?, gender = ?, city = ? where user_id = ?";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

		jdbcTemplate.update(sql,
		    new Object[] { user.getFirstName(), user.getLastName(),
		      user.getGender(), user.getCity(), user.getUserId() });*/
		
		String sql = "call sp_user_Update (?, ?, ?)";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.update(sql,
							user.getUserId(),
							user.getName(),
							user.getPassword());
	}

	@Override
	public void deleteData(String id) {
		String sql = "call sp_user_Delete (?)";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.update(sql, id);
	}

	@Override
	public User getUser(String id) {
		List<User> userList = new ArrayList<User>();
		String sql = "call sp_user_GetById (?)";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		userList = jdbcTemplate.query(sql, new UserRowMapper(), id);
		return userList.get(0);
	}
	
	@Override
	public User checkLogin(String name, String password) {
		try {
			List<User> userList = new ArrayList<User>();
			String sql = "call sp_user_CheckLogin (?, ?)";
			JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
			userList = jdbcTemplate.query(sql, new UserRowMapper(), name, password);
			return userList.get(0);
		} catch(Exception e) {
			return null;
		}
	}
}
